<?php
/**
 * 托管控制器
 * User: John
 * Date: 16-12-30
 * Time: 下午3:57
 */
namespace app\backend\controller;

use app\backend\controller\traits\AuthManager;
use app\backend\model\BillManager;
use app\backend\model\Building;
use think\Controller;
use app\backend\model\Trust;

class TrustController extends Controller
{
    use AuthManager;
    private $_memberId = null;
    private $_dtype    = null;
    private $_pdtype   = null;
    private $_pmid     = null;
    private $_allAuth  = [];
    public function __construct()
    {
        parent::__construct();
        $memberInfo = $this->getLoginInfo();
        $this->_memberId = $memberInfo['mid'];
        $this->_dtype    = $memberInfo['dtype'];
        $this->_pdtype   = $memberInfo['p_dtype'];
        $this->_pmid     = $memberInfo['p_mid'];
        $this->_allAuth  = $this->getPower($this->_memberId, $this->_dtype);
    }

    /**
     * 生成托管订单数据
     * @date   2017-1-22
     * @author wuhao
     *
     * @param  array  $rateArr     分成比例数组
     * @param  int    $buildingId  楼宇ID
     * @param  int    $houseId     房源编号
     * @param  int    $ownerId     业主id
     * @param  int    $mobile      业主电话
     * @param  int    $settleType  结算类型 1=年 2=月
     * @param  int    $dozenMoney  保底金额
     * @param  int    $billingDay  账单日
     * @param  int    $beginTime   托管起始时间
     * @param  int    $endTime     托管结束时间
     *
     * @return json
     */
    public function addTrustInfo()
    {
        if (!in_array($this->getOper('add_trust'), $this->_allAuth)) {
            $this->apiReturn(400,[],'无权操作');
        }

        $rateArr     = I('post.rate_arr');//分成比例数组
        $buildingId  = I('post.building', 0, 'intval');
        $houseId     = I('post.house', '', 'strval');
        $ownerId     = I('post.owner_id', 0, 'intval');
        $mobile      = I('post.mobile', '', 'strval');
        $settleType  = I('post.settle_type', 0, 'intval');
        $dozenMoney  = I('post.money', 0, 'intval');
        $billingDay  = I('post.billing_day', 0, 'strval');
        $beginTime   = I('post.begin_time', 0, 'strval');
        $endTime     = I('post.end_time', 0, 'strval');

        $rateArr = json_decode($rateArr, true);
        if (!$buildingId || !$houseId || !$mobile || !strtotime($beginTime)|| !strtotime($endTime)|| !$settleType|| !$billingDay
            || !$ownerId || !is_numeric($dozenMoney) || $dozenMoney<0 ||!is_array($rateArr)) {
            $this->apiReturn(400, [], '参数有误！');
        }

        foreach ($rateArr as $rate) {
            if ((!is_numeric($rate['rental'])) || (!is_numeric($rate['split'])) || $rate['rental'] <0 || $rate['rental'] >100
                || $rate['split'] <0 || $rate['split'] >100) {
                $this->apiReturn(400, [], '参数有误！');
            }
        }

        $rentalArr = array_column($rateArr, 'rental');
        if (count($rateArr) != count(array_unique($rentalArr))) {
            $this->apiReturn(400, [], '比例设置不能存在一样的！');
        }

        $beginTime   = strtotime($beginTime);
        $endTime     = strtotime($endTime);
        $houseIdArr  = explode(',', $houseId);

        if ($settleType == 1) {
            $cycleMark = date('Ym', strtotime('+1 year')).handleDay($billingDay);   //年标记，先生成下一年的启动日
        } else {
            $cycleMark = date('Ym', strtotime('+1 month')).handleDay($billingDay);  //月标记，先生成下一月的启动日
        }

        //托管订单id生成
        $orderId = time() . genRandomNum(2);

        $trustModel  = new Trust();

        //检查是否已有对应的托管订单
        $res = $trustModel->getSettleOrder($ownerId, $this->_pmid, $buildingId);
        if ($res) {
            $this->apiReturn(400, [], "已有对应的托管订单了,不能重复添加");
        }

        //检查是否已有对应的分成比例数据
        foreach ($rateArr as $r) {
            $check = $trustModel->checkShareRule($orderId, $r['rental'], $ownerId, $this->_pmid);
            if ($check) {
                $this->apiReturn(400, [], "托管订单:$orderId,出租率:".$r['rental'].",业主id:$ownerId,托管公司id:$this->_pmid 已存在，不能重复添加");
            }
        }

        //添加托管订单数据
        $res  = $trustModel->addSettleOrder($buildingId, $ownerId, $this->_pmid,  $settleType, $dozenMoney, $billingDay, $beginTime,
            $endTime, $cycleMark, $orderId);

        if ($res) {
            $status = 1;
            foreach ($rateArr as $v) {
                //100-split存的是托管的比例
                $res2 = $trustModel->addShareRule($orderId, intval($v['rental']), 100 - intval($v['split']), $ownerId, $this->_pmid);
                if (!$res2) {
                    $status = 0;
                    zft_log('trust/add_sharing_rule_fail', $trustModel->getLastSql());
                }
            }

            $buildModel = new Building();
            $status2 = 1;
            //设置这栋楼的所有该业主的楼栋的未出租的为托管的房间为托管状态
            $data  = ['trust_status' => 1, 'trust_id'=>$this->_pmid];
            $where = [
                'mid'         => $ownerId,
                'building_id' => $buildingId,
                'status'      => 2,//未出租状态的
                'trust_status'=> 0,//未托管
            ];
            $updateHouse = $buildModel->updateHouse($data, $where);
            if (!$updateHouse) {
                $status2 = 0;
                zft_log('build/update_house_fail', $buildModel->getLastSql());
            }

            if ($status == 0 && $status2 == 1) {
                $this->apiReturn(200, [], '设置托管信息成功,但有分成比例设置失败');
            } elseif ($status2 == 0 && $status == 1) {
                $this->apiReturn(200, [], '设置托管信息成功,但有房屋设置失败');
            } elseif ($status2 == 0 && $status == 0) {
                $this->apiReturn(200, [], '设置托管信息成功,但有分成比例设置和房屋状态设置失败');
            } else {
                $this->apiReturn(200, [], '设置成功');
            }
        } else {
            zft_log('trust/add_settle_order_fail', "添加楼栋：$buildingId，房源:$houseId, 业主id :$ownerId 失败");
            $this->apiReturn(201, [], '设置失败');
        }
    }

    /**
     * 获取我的合同
     * @date   2017-01-23
     * @author wuhao
     *
     * @param int  $page  页数
     * @param int  $pageSize  每页个数
     * @return json
     */
    public function getMyOrder()
    {
        if (!in_array($this->getOper('trust_list'), $this->_allAuth)) {
            $this->apiReturn(400,[],'无权操作');
        }
        $page     = I('post.page', 1, 'intval');
        $pageSize = I('post.page_size', 3, 'intval');
        if (!is_numeric($page) || $page<=0 || !is_numeric($pageSize) || $pageSize<=0) {
            $this->apiReturn(400, [], "参数错误!");
        }

        $trustModel = new Trust();
        $buildModel = new Building();
        $res = $trustModel->getMyOrder($this->_pmid, $this->_pdtype, $page, $pageSize);

        if (!$res) {
            $this->apiReturn(205, [], '没有数据');
        }

        foreach ($res['list'] as $k => $v) {
            //判断实际生效状态
            if ($v['begintime'] > time()) {
                $res['list'][$k]['status'] = 0;//未生效
            } else {
                $res['list'][$k]['status'] = 1;
            }

            //转化时间
            $res['list'][$k]['begintime'] = date('Y-m-d', $v['begintime']);
            $res['list'][$k]['endtime']   = date('Y-m-d', $v['endtime']);

            //获取门牌号信息
            $houseInfo = $buildModel->getHouseRoom($v['building_id'], $v['owner_id']);
            $res['list'][$k]['room'] = '';
            if (!$houseInfo) {
                $res['list'][$k]['room'] = '';
            } else {
                foreach ($houseInfo as $a => $b) {
                    $res['list'][$k]['room'] .= $b['room'].',';
                }
                $res['list'][$k]['room'] = rtrim($res['list'][$k]['room'], ',');
            }
        }
        $this->apiReturn(200, $res, '查询成功');
    }

    /**
     * 获取我的合同详细信息
     * @date   2017-01-23
     * @author wuhao
     *
     * @param string  $settleNum  订单号
     * @return json
     */
    public function getOrderDetail()
    {
        if (!in_array($this->getOper('trust_list'), $this->_allAuth)) {
            $this->apiReturn(400,[],'无权操作');
        }
        $settleNum = I('post.settlenum', '', 'strval');
        if (!$settleNum) {
            $this->apiReturn(400, [], "参数错误!");
        }

        $trustModel = new Trust();
        $res = $trustModel->getOrderDetail($settleNum);

        if (!$res) {
            $this->apiReturn(204, [], "没有数据!");
        } else {
            $ruleInfo           = $trustModel->getRuleDetail($settleNum);
            if ($ruleInfo) {
                foreach ($ruleInfo as $k => $v) {
                    //转化为业主的分成比例
                    $ruleInfo[$k]['split_ratio'] = 100 - $ruleInfo[$k]['split_ratio'];
                }
            }
            $res['rate']        = $ruleInfo;
            $res['begintime']   = date('Y-m-d', $res['begintime']);
            $res['endtime']     = date('Y-m-d', $res['endtime']);
            $res['dozen_money'] = yuan($res['dozen_money']);
        }
        $this->apiReturn(200, $res, "");
    }

    /**
     * 编辑托管信息
     * @date   2017-1-22
     * @author wuhao
     *
     * @param  array  $rateArr     分成比例数组
     * @param  string $settleNum   托管订单id
     * @param  int    $settleType  结算类型 1=年 2=月
     * @param  int    $dozenMoney  保底金额
     * @param  int    $billingDay  账单日
     * @param  int    $beginTime   托管起始时间
     * @param  int    $endTime     托管结束时间
     *
     * @return json
     */
    public function setTrust()
    {
        if (!in_array($this->getOper('add_trust'), $this->_allAuth)) {
            $this->apiReturn(400,[],'无权操作');
        }
        $rateArr     = I('post.rate_arr');//分成比例数组
        $settleNum   = I('post.settlenum', 0, 'strval');
        $ownerId     = I('post.owner_id', 0, 'intval');
        $settleType  = I('post.settle_type', 0, 'intval');
        $dozenMoney  = I('post.money', 0, 'intval');
        $billingDay  = I('post.billing_day', 0, 'strval');
        $beginTime   = I('post.begin_time', 0, 'strval');
        $endTime     = I('post.end_time', 0, 'strval');

        $rateArr = json_decode($rateArr, true);
        if (!$settleNum|| !$beginTime|| !$endTime|| !$settleType|| !$billingDay
           || !is_numeric($dozenMoney) ||!is_array($rateArr)) {
            $this->apiReturn(400, [], '参数错误');
        }

        foreach ($rateArr as $key => $rate) {
            if ((!is_numeric($rate['rental'])) || (!is_numeric($rate['split'])) || $rate['rental'] <0 || $rate['rental'] >100
                || $rate['split'] <0 || $rate['split'] >100) {
                $this->apiReturn(400, [], '参数有误！');
            }
            //转化为业主分成比例
            $rateArr[$key]['split'] = 100 - $rateArr[$key]['split'];
        }

        if (!$this->checkAuth($this->dtype, 'editTrust')) {
            $this->apiReturn(201, [], '无权操作');
        }

        $rentalArr = array_column($rateArr, 'rental');
        if (count($rateArr) != count(array_unique($rentalArr))) {
            $this->apiReturn(400, [], '比例设置不能存在一样的！');
        }

        $trustModel = new Trust();

        //判断是否有权限修改
        $auth1 = $trustModel->checkAuth($settleNum, $this->_pmid, 'rule');
        $auth2 = $trustModel->checkAuth($settleNum, $this->_pmid, 'order');
        if (!$auth1 || !$auth2) {
            $this->apiReturn(400, [], '没有权限');
        }

        //判断是否在托管起始时间之前
        $time = $trustModel->getTrustBeginTime($settleNum);
        if ($time['begintime'] < time()) {
            $this->apiReturn(400, [], '托管合约已生效，不能修改');
        }

        if ($settleType == 1) {
            $cycleMark = date('Ym', strtotime('+1 year')).handleDay($billingDay);   //年标记，先生成下一年的启动日
        } else {
            $cycleMark = date('Ym', strtotime('+1 month')).handleDay($billingDay);  //月标记，先生成下一月的启动日
        }
        //设置修改信息
        $res  = $trustModel->setSettleOrder($settleNum, $settleType, $dozenMoney, $billingDay, $beginTime, $endTime, $cycleMark);
        if ($res) {
            $res1 = $trustModel->setSharingRule($settleNum, $ownerId, $rateArr, $this->_pmid);
            if ($res1['code'] == 200) {
                $this->apiReturn(200, [], '设置成功');
            } else {
                $this->apiReturn(200, [], '托管规则分成比例有设置失败的地方');
            }
        } else {
            zft_log('trust/set_settle_order_fail', $trustModel->getLastSql());
            $this->apiReturn(201, [], '设置失败，请稍后重试');
        }
    }

    /**
     * 使托管合同失效
     * @date   2017-1-22
     * @author wuhao
     *
     * @param  string $settleNum   托管订单id
     * @param  int    $status      合同状态 0=失效
     *
     * @return json
     */
    public function forbidTrust()
    {
        if (!in_array($this->getOper('forbid_trust'), $this->_allAuth)) {
            $this->apiReturn(400,[],'无权操作');
        }
        $settleNum   = I('post.orderid', '', 'strval');
        $status      = I('post.status', -1, 'intval');
        if (!$settleNum || !in_array($status, [0])) {
            $this->apiReturn(400, [], '参数有误');
        }
        $trustModel = new Trust();
        //先获取信息
        $trustInfo = $trustModel->getTrustedInfo(['orderid' => $settleNum], 'id, trust_id, status, building_id, owner_id');

        if (!$trustInfo) {//找不到合约信息
            $this->apiReturn(202, [], '没有相应的合同信息');
        }
        if ($this->memberId != $trustInfo[0]['trust_id']) { //登录人不是合同的托管方
            $this->apiReturn(203, [], '无权操作');
        }
        if ($status == $trustInfo[0]['status']) {//当前状态已经是想要修改的状态了
            $this->apiReturn(204, [], '状态无需重复修改');
        }

        //判断合约下的房源是否已经出租出去了
        $buildModel = new Building();
        $state      = $buildModel->getHouseInfoByUser($trustInfo[0]['owner_id'], $trustInfo[0]['building_id'], 'status');
        $state      = array_column($state, 'status');
        if (in_array(1, $state)) {
            $this->apiReturn(205, [], '已有房屋出租了,不能失效');
        }

        //更新合同状态
        $res = $trustModel->forbidTrust($settleNum, $status);
        if ($res) {
            //更新托管账单为失效
            $billModel = new BillManager();
            $s = $billModel->updateTrustBill(['ordernum' => $settleNum, 'is_delete' => 0], ['is_delete' => 1]);
            if (!$s) {
                zft_log('bill/trust_bill', $billModel->getLastsql());
            }
            //更新房源状态为未托管
            $update1 = $buildModel->updateHouse(['trust_status' => 0, 'trust_id'=>0],['mid' => $trustInfo[0]['owner_id'], 'building_id' => $trustInfo[0]['building_id']]);
            if (!$update1) {
                zft_log('bill/trust_bill_update_house', $buildModel->getLastsql());
            }
            $this->apiReturn(200, [], '操作成功');
        } else {
            zft_log('trust/update_trust', $trustModel->getLastSql());
            $this->apiReturn(205, [], '操作失败,请稍后再试');
        }
    }
}
